<script setup lang="ts">
import { ref, onMounted } from 'vue'
const preview = ref(null), imgUrl = ref(null)

onMounted(() => {
  document.addEventListener('paste', function (event) {
    let items = event.clipboardData && event.clipboardData.items
    let file = null
    if (items && items.length) {
      // 检索剪切板items
      for (let i = 0; i < items.length; i++) {
        if (items[i].type.indexOf('image') !== -1) {
          file = items[i].getAsFile()
          break
        }
      }
    }
    // 此时file就是剪切板中的图片文件
    let reader = new FileReader()
    reader.onload = function(event) {
      // event.target.result就是图片的Base64地址啦
      // imgUrl.value.src=reader.result
      // imgUrl.value.src=event.target.result
      preview.value.innerHTML = `<img src="${event.target.result}" class="upload-image">`
      console.log(event)
    }
    reader.readAsDataURL(file)
  })
})

</script>

<template>
  <div ref="preview" class="upload-preview w-60 h-30 border border-dashed border-black"></div>
<!--  <img ref="imgUrl" class="w-48 h-24 border border-black"><br/>-->
</template>

<style scoped lang="scss">
.upload-preview:empty::before {
  border: 1px solid #ddd;
  content: '预览区';
  display: block;
  text-align: center;
  font-size: 20px;
  line-height: 120px;
  opacity: .6;
}
</style>